package com.tim.app.ui.adapter.comment;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.TimeUtil;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.roundimg.RoundedImageView;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.callback.ReplyCallback;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.ActionStateMsg;
import com.tim.app.server.entry.Comment;
import com.tim.app.server.entry.ReplyComment;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.ActionResult;
import com.tim.app.server.result.ReplyResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.selected.ArticleDetailActivity;
import com.tim.app.ui.activity.selected.CommentDetailActivity;
import com.tim.app.ui.activity.some_homepage.SomeoneHomepageActivity;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;

import cn.carbs.android.expandabletextview.library.ExpandableTextView;


/**
 * 评论列表的适配器
 */
public class CommentInfoAdapter extends BaseRecyclerAdapter<BaseRecyclerAdapter.BaseRecyclerViewHolder, Comment> {

    public static final String TAG = "CommentInfoAdapter";

    private Context mContext;
    private String type;
    private String typeId;

    private Comment replyComment;
    private int position;

    public CommentInfoAdapter(Context mContext, List<Comment> mDataList, String type, String typeId) {
        super(mDataList);
        this.mContext = mContext;
        this.type = type;
        this.typeId = typeId;
    }

    @Override
    public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        BaseRecyclerViewHolder holder = null;
        holder = new InfoViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_content_comment_info, parent, false));
        return holder;
    }

    @Override
    public void onBindViewHolder(BaseRecyclerViewHolder mHolder, final int position, final Comment data) {
        if (null == data)
            return;
        final InfoViewHolder holder = (InfoViewHolder) mHolder;

        if (null != data.getUserMsg()) {
            if (!TextUtils.isEmpty(data.getUserMsg().getImage())) {
                BitmapLoader.ins().loadImage(data.getUserMsg().getImage(), holder.rivAvatar);
            } else {
                BitmapLoader.ins().loadImage("", holder.rivAvatar);
            }
            if (!TextUtils.isEmpty(data.getUserMsg().getName())) {
                holder.tvUserName.setText(data.getUserMsg().getName());
            } else {
                holder.tvUserName.setText("");
            }
        } else {
            BitmapLoader.ins().loadImage("", holder.rivAvatar);
            holder.tvUserName.setText("");
        }

        holder.rivAvatar.setTag(data);
        holder.tvUserName.setTag(data);
        holder.rivAvatar.setOnClickListener(onClickListener);
        holder.tvUserName.setOnClickListener(onClickListener);
        if (!TextUtils.isEmpty(data.getContent())) {
            holder.etvComment.setText(data.getContent());
        } else {
            holder.etvComment.setText("");
        }
        if (null != data.getActionStateMsg() && null != data.getActionStateMsg().getAgreeState()) {
            holder.tvPriseNumber.setSelected(true);
        } else {
            holder.tvPriseNumber.setSelected(false);
        }
        if (UserManager.ins().isLogin() && null != data.getUserMsg() && !TextUtils.isEmpty(data.getUserMsg().getUserId()) && data.getUserMsg().getUserId().equals(UserManager.ins().getUserId())) {
            holder.tvDelete.setVisibility(View.VISIBLE);
        } else {
            holder.tvDelete.setVisibility(View.GONE);
        }
        if(data.getAgreeCount()>0){
            holder.tvPriseNumber.setText(String.valueOf(data.getAgreeCount()));
        }else{
            holder.tvPriseNumber.setText("赞");
        }
        holder.tvReplyTime.setText(TimeUtil.formatTimeRuleOne(mContext, data.getCreateTime()));
        holder.tvPriseNumber.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(mContext);
                    return;
                }
                if (null != data.getUserMsg() && !TextUtils.isEmpty(data.getUserMsg().getUserId()) && data.getUserMsg().getUserId().equals(UserManager.ins().getUserId())) {
                    ToastUtil.showToast("不能对自己的评论进行点赞");
                    return;
                }
                addPriseOrCancelPrise(holder.tvPriseNumber, data, position);
            }
        });

        holder.tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteComment(holder.tvDelete, position);
            }
        });
//        if (null != data.getUserMsg() && !TextUtils.isEmpty(data.getUserMsg().getUserId()) && data.getUserMsg().getUserId().equals(UserManager.ins().getUserId())) {
//            holder.tvReply.setVisibility(View.GONE);
//        } else {
        holder.tvReply.setVisibility(View.VISIBLE);
        holder.tvReply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventManager.ins().sendEvent(EventTag.ON_SELECT_PEPLY, Integer.valueOf(typeId), 0, data);
                setReplyComment(data, position);
            }
        });
//        }
        if (data.getReplyCount() > 0) {
            holder.llRepltCommentContainer.setVisibility(View.VISIBLE);
            holder.tvReplyCommentCount.setText(mContext.getString(R.string.replyCommentCount, String.valueOf(data.getReplyCount())));
            if (null != data.getReplyList() && data.getReplyList().size() > 0) {
                holder.tvReplyUserName.setText(data.getReplyList().get(0).getUserName() + ":");
                holder.tvReplyComment.setText(data.getReplyList().get(0).getContent());
            }
            holder.llRepltCommentContainer.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    CommentDetailActivity.start(mContext, data.getId(), false);
                }
            });
        } else {
            holder.llRepltCommentContainer.setVisibility(View.GONE);
        }

    }

    public Comment getReplyComment() {
        return replyComment;
    }

    public void setReplyComment(Comment replyComment, int position) {
        this.replyComment = replyComment;
        this.position = position;
    }

    /**
     * 回复评论
     *
     * @param content
     * @param callback
     */
    public void postReplyComment(String content, final ReplyCallback callback) {
        final Comment comment = getReplyComment();
        if (null == comment)
            return;
        API_Found.ins().addCommentReply(TAG, comment.getId(), comment.getUserMsg().getUserId(), comment.getUserMsg().getName(), content, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    ReplyResult result = new Gson().fromJson(resultValue, ReplyResult.class);
                    if (null != result && null != result.getRes()) {
                        ReplyComment replyComment = result.getRes().getReply();
                        if (position > -1) {
                            comment.setReplyCount(comment.getReplyCount() + 1);
                            if (null == comment.getReplyList()) {
                                comment.setReplyList(new ArrayList<ReplyComment>());
                            }
                            comment.getReplyList().add(0, replyComment);
                            getDataList().set(position, comment);
                            notifyDataSetChanged();
                        }
                        if (null != callback) {
                            callback.onSuccess();
                        }
                    } else {
                        if (null != callback) {
                            callback.onFail();
                        }
                    }
                } else if (ResponseResult.ResultStatus.BE_ADD_BLACK == errCode) {
                    ToastUtil.showToast("由于对方的设置，你不能回复此评论");
                } else {
                    if (null != callback) {
                        callback.onFail();
                    }
                }
                return false;
            }
        });
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Comment comment = (Comment) v.getTag();
            SomeoneHomepageActivity.start(mContext, comment.getUserMsg(), false);
        }
    };

    /**
     * 删除评论
     *
     * @param position
     */
    private void deleteComment(final View deleteView, final int position) {
        deleteView.setEnabled(false);
        Comment comment = getDataList().get(position);
        API_User.ins().deleteComment(ArticleDetailActivity.TAG, comment.getId(), type, typeId, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                deleteView.setEnabled(true);
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    EventManager.ins().sendEvent(EventTag.ON_COMMENT_DELETED, 0, 0, position);
                    ToastUtil.showToast("删除成功");
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    /**
     * 赞/取消赞
     */
    public void addPriseOrCancelPrise(final TextView tvPriseNumber, final Comment data, final int position) {
        tvPriseNumber.setEnabled(false);
        if (null != data.getActionStateMsg() && data.getActionStateMsg().getAgreeState() != null) {
            int id = data.getActionStateMsg().getAgreeState();
            API_User.ins().cancelPrise(TAG, UserManager.ins().getUserId(), AppKey.TYPE_COMMENT, data.getId(), AppKey.AGREE, id, data.getUserMsg().getUserId(), new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    tvPriseNumber.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        data.setAgreeCount(data.getAgreeCount() - 1);
                        data.getActionStateMsg().setAgreeState(null);
                        getDataList().set(position, data);
                        notifyDataSetChanged();
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        } else {
            API_User.ins().addPrise(TAG, UserManager.ins().getUserId(), AppKey.TYPE_COMMENT, data.getId(), AppKey.AGREE, data.getUserMsg().getUserId(), new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    tvPriseNumber.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        ActionResult result = new Gson().fromJson(resultValue, ActionResult.class);
                        if (null != result && null != result.getRes()) {
                            if (null == data.getActionStateMsg()) {
                                data.setActionStateMsg(new ActionStateMsg());
                            }
                            data.getActionStateMsg().setAgreeState(result.getRes().getAction().getId());
                            data.setAgreeCount(data.getAgreeCount() + 1);
                        }
                        getDataList().set(position, data);
                        notifyDataSetChanged();
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        }
    }


    public class InfoViewHolder extends BaseRecyclerViewHolder {

        RoundedImageView rivAvatar;
        TextView tvUserName;
        ExpandableTextView etvComment;
        TextView tvPriseNumber;
        TextView tvReply;
        TextView tvReplyTime;
        TextView tvDelete;
        LinearLayout llRepltCommentContainer;
        TextView tvReplyUserName;
        TextView tvReplyComment;
        TextView tvReplyCommentCount;

        public InfoViewHolder(View itemView) {
            super(itemView);
            rivAvatar = (RoundedImageView) itemView.findViewById(R.id.rivAvatar);
            tvUserName = (TextView) itemView.findViewById(R.id.tvUserName);
            tvReply = (TextView) itemView.findViewById(R.id.tvReply);
            tvPriseNumber = (TextView) itemView.findViewById(R.id.tvPriseNumber);
            tvReplyTime = (TextView) itemView.findViewById(R.id.tvReplyTime);
            etvComment = (ExpandableTextView) itemView.findViewById(R.id.etvComment);
            tvDelete = (TextView) itemView.findViewById(R.id.tvDelete);
            llRepltCommentContainer = (LinearLayout) itemView.findViewById(R.id.llRepltCommentContainer);
            tvReplyUserName = (TextView) itemView.findViewById(R.id.tvReplyUserName);
            tvReplyComment = (TextView) itemView.findViewById(R.id.tvReplyComment);
            tvReplyCommentCount = (TextView) itemView.findViewById(R.id.tvReplyCommentCount);
        }

    }

}
